package com.masterclient.app.businessmodule.minemodule.address;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.bean.address.AddResultBean;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.eoner.baselibrary.bean.address.AddressListBean;
import com.eoner.baselibrary.bean.address.City;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.UtilCollection;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.minemodule.address.contract.AddNewAddressContract;
import com.masterclient.app.businessmodule.minemodule.address.contract.AddNewAddressPresenter;
import com.suke.widget.SwitchButton;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 作者：sean
 * 创建时间：2017/7/31 10:40
 * 功能说明：
 */

@RuntimePermissions
public class AddNewAddressActivity extends FCBusinessActivity<AddNewAddressPresenter> implements AddNewAddressContract.View {


    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_shr)
    TextView tvShr;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.rl_right)
    RelativeLayout rlRight;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.tag_default)
    TextView tagDefault;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.ll_choose_area)
    LinearLayout llChooseArea;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;

    @BindView(R.id.address_default_view)
    RelativeLayout defaultView;
    @BindView(R.id.zsq_address_commit)
    TextView zsq_address_commit;

    private boolean isGiving = false;
    private String username, usernumber;
    Intent mIntent;
    private AddressSelectDialog dialog;
    private String mPositon = "3";
    String cityId;
    String address1,address2,address3;

    private String default_address = "0";
    private String isPurchase = "0";
    RxPermissions rxPermissions;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_add_new_address;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("编辑收货地址");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        //判断是否是赠送品
        isPurchase  = getIntent().getStringExtra("isPurchase");
        String giving  = getIntent().getStringExtra("isGiving");
        if (giving != null && giving.length() > 0) {
            if (giving.equals("1")) {
                isGiving = true;
            }
        }

        if (isGiving) {
            mNavigationBar.setTitle("添加获赠人地址");
            defaultView.setVisibility(View.GONE);
            zsq_address_commit.setVisibility(View.VISIBLE);
            tvSave.setVisibility(View.GONE);
        } else {
            mNavigationBar.setTitle("添加新地址");
            defaultView.setVisibility(View.VISIBLE);
            zsq_address_commit.setVisibility(View.GONE);
        }

        etName.setHintTextColor(Color.parseColor("#999FAA"));
        etPhone.setHintTextColor(Color.parseColor("#999FAA"));
        etAddressDetail.setHintTextColor(Color.parseColor("#999FAA"));
        rxPermissions = new RxPermissions(this);
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if(isChecked){
                    default_address = "1";
                }else {
                    default_address = "0";
                }
            }
        });
    }

    @OnClick({R.id.rl_right,R.id.tv_area,R.id.ll_choose_area,R.id.tv_save,R.id.zsq_address_commit}) void onClick(View view){
        switch (view.getId()){
            case R.id.rl_right:

                rxPermissions
                        .requestEach(Manifest.permission.READ_CONTACTS)
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
                            } else if (permission.shouldShowRequestPermissionRationale){
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });

                break;
            case R.id.tv_area:
                openAreaDialog();
                break;
            case R.id.ll_choose_area:
                openAreaDialog();
                break;
            case R.id.tv_save:
            case R.id.zsq_address_commit:
                String address = etAddressDetail.getText().toString().trim();
                String uname  =etName.getText().toString().trim();
                String uphone = etPhone.getText().toString().trim();
                if(TextUtils.isEmpty(address)){
                    showToast("地址不能为空");
                    return;
                }
                if(!UtilCollection.isAddress(address)){
                    showToast("收货地址只允许 中文 英文 数字 - # 空格 中英文括号！");
                    return;
                }
                if(TextUtils.isEmpty(cityId)){
                    showToast("请选择城市");
                    return;
                }
                if(TextUtils.isEmpty(uname)){
                    showToast("请填写收货人");
                    return;
                }
                if(!StringsUtils.isPhoneNum(uphone)){
                    showToast("手机号码格式错误");
                    return;
                }
                baseShowCommitLoading("正在加载...");
                mPresenter.addNewAddress(cityId,address.replace(" ",""),default_address,uname,uphone);
                break;
        }
    }

    private void openAreaDialog() {
        dialog = new AddressSelectDialog(mContext,isPurchase);
        dialog.setOnSelectListener(new AddressSelectDialog.OnSelectListener() {
            @Override
            public void onSelect(String position, String id,String address) {
                mPositon = position;
                mPresenter.getRegionList(id);
                if("4".equals(position)){
                    address1 = address;
                }else if("5".equals(position)){
                    address2 = address;
                }
            }

            @Override
            public void onSelected(String id,String name) {
                cityId = id;
                address3 = name;
                tvArea.setText(address1+" "+address2+" "+address3);
                tvArea.setTextColor(Color.parseColor("#141922"));
                dialog.dismiss();
            }
        });
        dialog.show();
        mPresenter.getRegionList("0");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                //申请授权，第一个参数为要申请用户授权的权限；第二个参数为requestCode 必须大于等于0，主要用于回调的时候检测，匹配特定的onRequestPermissionsResult。
                //可以从方法名requestPermissions以及第二个参数看出，是支持一次性申请多个权限的，系统会通过对话框逐一询问用户是否授权。
                mIntent = data;
                getUserInfo(data);
            }else{
                //如果该版本低于6.0，或者该权限已被授予，它则可以继续读取联系人。
                getUserInfo(data);
            }
        }
    }

    @Override
    protected void onPause() {
        hideSoftInput(etPhone);
        super.onPause();
    }

    @OnShowRationale(Manifest.permission.READ_CONTACTS)
    void showAllowRead(final PermissionRequest request){
        new AlertDialog.Builder(this)
                .setMessage("读取联系人权限")
                .setPositiveButton("确定", (dialog, button) -> request.proceed())
                .setNegativeButton("取消", (dialog, button) -> request.cancel())
                .show();
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void showDeniedForContact() {
        Toast.makeText(this, "拒绝", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void showNeverAskForContact() {
        Toast.makeText(this, "不再询问", Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void getUserInfo(Intent data) {
        // ContentProvider展示数据类似一个单个数据库表
        // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
        ContentResolver reContentResolverol = getContentResolver();
        // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
        Uri contactData = data.getData();
        // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
        Cursor cursor = managedQuery(contactData, null, null, null, null);
        if (cursor == null || cursor.getCount()<=0) return;
        boolean flag = false;
        if(cursor != null){
            flag = cursor.moveToFirst();
        }
        // 获得DATA表中的名字
        if(flag){
            username = cursor.getString(cursor
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        }
        // 条件为联系人ID
        String contactId = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts._ID));
        // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
        Cursor phone = reContentResolverol.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                        + contactId, null, null);
        while (phone != null && phone.moveToNext()) {
            usernumber = phone
                    .getString(phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            etName.setText(username);
            etPhone.setText(usernumber.replace(" ",""));
        }
    }

    @Override
    public void getAddressList(AddressListBean.DataBean dataBean) {
        ArrayList<City> arrayList = new ArrayList<>();
        for(AddressListBean.DataBean.ShItemsBean bean:dataBean.getSh_items()){
            City city = new City();
            city.setGrade(mPositon);
            city.setId(bean.getSh_id());
            city.setName(bean.getSh_name());
//            city.setIsMunicipality(bean.);
            arrayList.add(city);
        }
        dialog.setCities(arrayList);
    }

    @Override
    public void addAddressSuccess(AddResultBean.DataBean dataBean) {
        baseHiddenCommitLoading();
        if (isGiving) {
            showToast("提交成功");
            Observable.just("s").delay(2, TimeUnit.SECONDS).subscribe(s->finish());

//            private String sh_province_id;
//            private String sh_city_id;
//            private String sh_area_id;
//            private String sh_area;
//            private String sh_city;
//            private String sh_province;
//            private String sh_address;

            String address = etAddressDetail.getText().toString().trim();
            String uname  =etName.getText().toString().trim();
            String uphone = etPhone.getText().toString().trim();

            AddressBean.DataBean.ShItemsBean addressBean = new AddressBean.DataBean.ShItemsBean();
            addressBean.setSh_id(dataBean.getSh_address_id());
            addressBean.setSh_mobile(uphone);
            addressBean.setSh_full_name(uname);
            addressBean.setSh_address(address);
            addressBean.setSh_city_id(cityId);
            if (address1 != null) {
                addressBean.setSh_province(address1);
            }
            if (address2 != null) {
                addressBean.setSh_city(address2);
            }
            if (address3 != null) {
                addressBean.setSh_area(address3);
            }
            Intent intent = new Intent();
            intent.putExtra("default_address",addressBean);
            setResult(120,intent);
            finish();


        } else {
            showToast("添加地址成功");
            Observable.just("s").delay(2, TimeUnit.SECONDS).subscribe(s->finish());
            finish();
        }
    }

    @Override
    public void addAddressFailed(String msg) {
        baseHiddenCommitLoading();
        showToast(msg);
    }
}
